﻿using Conversive.PHPSerializationLibrary;
using Furion;
using Furion.DependencyInjection;
using Furion.Logging;
using Furion.Logging.Extensions;
using Furion.RemoteRequest.Extensions;
using Furion.TaskScheduler;
using Microsoft.Extensions.DependencyInjection;
using MqttModel;
using Newtonsoft.Json;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FaceMqttClient
{
    public class Wxsendworker
    {
        private readonly IDatabase dbredis;
        public string server = "https://weixin.tslexunbao.com";
        //        ConnectionMultiplexer redis;
        string pkey = "easywechat.kernel.access_token*";
        string key = "easywechat.kernel.access_token";
        PhpSerializer ps = new PhpSerializer();
        bool send = false;
        /// <summary>
        ///  微信token
        /// </summary>
        private string token;
        private readonly WechatApiClientOptions options;
        public Wxsendworker()
        {
            options = new WechatApiClientOptions()
            {
                AppId = "wx42a8bcc9d53bcf3b",
                AppSecret = "673321d209f6c3e3b4d8d9eb6fce56a6",
            };
            ConnectionMultiplexer redis = App.GetService<ConnectionMultiplexer>();
            var server = redis.GetServer("127.0.0.1", 6379);
            dbredis = redis.GetDatabase(0);

            foreach (var key in server.Keys(pattern: pkey))
            {
                //  Console.WriteLine(key);
                this.key = key;
                Console.WriteLine(key);
            }
        }
        /// <summary>
        /// 微信通知
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="count"></param>
        //[SpareTime(5000, "jobName1", StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        public void DoSomething1(SpareTimer timer, long count)
        {

         //   Scoped.Create((_, scope) =>
           {
              // var services = scope.ServiceProvider;
               try
               { 
                   var str = (dbredis.StringGet(key));
                   if (!String.IsNullOrEmpty(str))
                   {
                       var t = (Dictionary<object, object>)ps.Deserialize(str);
                       if (t.ContainsKey("access_token"))
                       {
                           token = t["access_token"].ToString();
                           // Console.WriteLine(token);
                           OnlineNoticeMe(token);
                           Console.ForegroundColor = ConsoleColor.White;

                            var wxtz = App.GetService<WeixinTongzhi>();// services.GetService<WeixinTongzhi>();
                           using (var unsend = wxtz.getUnsend())
                           {
                               // 获取小时数
                               var h = DateTime.Now.Hour;
                               foreach (DataRow kaoqin in unsend.Rows)
                               {
                                   try
                                   {
                                       StringLoggingPart.Default().SetMessage($"{kaoqin["address"]}  {kaoqin["clname"]} {kaoqin["username"]} 开始发送").LogWarning();
                                       
                                       using (var untz = wxtz.getTongzhi(kaoqin["uid"].ToString()))
                                       {

                                           foreach (DataRow guanzhu in untz.Rows)
                                           {
                                               var f= wxtz.cansend(guanzhu["slname"].ToString(), kaoqin).Result;
                                               if (f==true)
                                               {                                                                                             
                                                 BuildKaoqinMsg(token, kaoqin, guanzhu);
                                               }
                                               else {
                                                   Console.WriteLine($"{kaoqin["address"]}  {kaoqin["clname"]} {guanzhu["username"]} 不发送");
                                                   StringLoggingPart.Default().SetMessage($"{kaoqin["address"]}  {kaoqin["clname"]} {guanzhu["username"]} 不发送").LogWarning();

                                               }


                                           }


                                       }

                                       if (!kaoqin["sn"].ToString().Equals("00000"))
                                       {
                                           if (kaoqin["zschool"].ToString().Equals("是") || kaoqin["dx"].ToString().Equals("是"))
                                           {
                                               if (wxtz.LeaveSchool(kaoqin["slname"].ToString()))
                                               {
                                                   //仅仅是住宿生发信息
                                                   if (
                                                       (h >= 11 && h <= 13) || // 中午
                                                       (h >= 16 && !wxtz.Isholiday(DateTime.Now.AddDays(1)).Result && kaoqin["zschool"].ToString().Equals("是")) // 下午 明天不是假期
                                                    )
                                                   {
                                                       // 中午

                                                       using (var tctz = wxtz.getTongzhiTeacher(kaoqin["classname"].ToString()))
                                                       {

                                                           if (tctz != null)
                                                           {

                                                               foreach (DataRow laoshi in tctz.Rows)
                                                               {

                                                                   LevelMsg(token, kaoqin, laoshi);

                                                               }
                                                           }

                                                       }
                                                   }
                                               }
                                           }
                                       }

                                   }
                                   catch (Exception e)
                                   {
                                       StringLoggingPart.Default().SetMessage($"{e.Message} ").LogError();

                                       Console.ForegroundColor = ConsoleColor.Red;
                                       Console.WriteLine(e.Message);
                                       Console.ForegroundColor = ConsoleColor.White;
                                   }
                                   wxtz.Sended(Convert.ToInt32(kaoqin["Lid"]));
                               }

                           }
                       }
                   }

               }
               catch (Exception e)
               {
                   StringLoggingPart.Default().SetMessage($"{e.Message} ").LogError();
                   Console.ForegroundColor = ConsoleColor.Red;
                   Console.WriteLine("微信通知 失败 " + e.Message);
               }

           }
            //);
            //Console.WriteLine("微信通知" + count);
        }

        /// <summary>
        /// 发送考勤通知
        /// </summary>
        /// <param name="token"></param>
        /// <param name="stu"></param>
        /// <param name="jiazhang"></param>
        private void BuildKaoqinMsg(string token, DataRow stu, DataRow jiazhang)
        {


            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.学生刷脸;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            string msg = "有一条考勤消息";
            if (stu["sn"].ToString().Equals("00000"))
            {
                msg = "已到课堂";
            }
            int stat = Convert.ToInt32(stu["state"]);
            switch (stat)
            {
                case 1:
                    // 未到
                    msg = "点名时未到课堂。";
                    break;
                case 2:
                    // 请假
                    msg = "请假未到课堂。";
                    break;
                case 3:
                    // 迟到
                    msg = "课堂点名迟到。";
                    break;
                default:
                    break;
            }

            int io = Convert.ToInt32(stu["io"]);
            switch (io)
            {
                case 1:
                    msg = "已经进校";
                    break;

                case 2:
                    msg = "已经离校";
                    break;
            }

            string adname = "";
            int adid = Convert.ToInt32(stu["adid"]);
            if (adid > 0)
            {
                var kls= App.GetService<Kaoqin_logService>();
                var ad = kls.getAdbyid(adid);
                if (ad != null) {
                    adname = ad.title + "提醒您";
                }
            }
            // 头
            tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"亲爱的{jiazhang["username"]}家长,{adname} {jiazhang["username"]}同学{msg}", Color = "#173177" });
            // 姓名
            tplr.Data.Add("name", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = jiazhang["username"].ToString(), Color = "#173177" });
            // 时间
            tplr.Data.Add("time", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = stu["time"].ToString(), Color = "#173177" });
            // 地点
            tplr.Data.Add("location", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = stu["address"].ToString(), Color = "#173177" });
            // 备注
            tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "点击这里查看详情\n↓↓↓↓↓↓↓", Color = "#ff0000" });
#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = jiazhang["oauth_id"].ToString();
#endif
            tplr.AccessToken = token;
            tplr.Url = "http://weixin.tslexunbao.com/user/kaoqin_log/index/" + stu["uid"];



            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr).ContinueWith((res =>
            {
                Console.WriteLine($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm")} {stu["clname"]} {jiazhang["username"]} {   tplr.ToUserOpenId }->{stu["Lid"]}  {res.Result.ErrorMessage}");

                StringLoggingPart.Default().SetMessage($"{stu["address"]}  {stu["clname"]} {jiazhang["username"]}  {JsonConvert.SerializeObject( tplr)}{   tplr.ToUserOpenId }->{stu["Lid"]}  {res.Result.ErrorMessage}").LogWarning();
            }));

        }


        /// <summary>
        /// 发送到期续费通知
        /// </summary>
        /// <param name="token"></param>
        /// <param name="stu"></param>
        /// <param name="jiazhang"></param>
        private void BuildXufeiMsg(string token, DataRow stu, DataRow jiazhang)
        {


            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.交费提醒;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            string msg = "的移动平安校园服务急需续费";
          


            // 头
            tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"亲爱的{jiazhang["username"]}家长, {jiazhang["username"]}同学{msg}", Color = "#173177" });
            // 姓名
            tplr.Data.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = jiazhang["username"].ToString(), Color = "#173177" });
            // 时间
            tplr.Data.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "进出校消息提醒/公共电话/成绩分析/直饮水等", Color = "#173177" });
            // 地点
            tplr.Data.Add("keyword3", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "90元/年或开通移动手机扣费10元/月", Color = "#173177" });
            // 备注
            tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "为了不影响您的使用，请尽快续费，如有疑问咨询客服。", Color = "#ff0000" });
#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = jiazhang["oauth_id"].ToString();
#endif
            tplr.AccessToken = token;
            tplr.Url = "https://weixin.tslexunbao.com/product/index/17?uid=" + stu["user_id"];



            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr).ContinueWith((res =>
            {
                Console.WriteLine($"续费 {DateTime.Now.ToString("yyyy/MM/dd HH:mm")} {stu["clname"]} {jiazhang["username"]} {tplr.ToUserOpenId}->{stu["Lid"]}  {res.Result.ErrorMessage}");

                StringLoggingPart.Default().SetMessage($"续费 {stu["address"]}  {stu["clname"]} {jiazhang["username"]}  {JsonConvert.SerializeObject(tplr)}{tplr.ToUserOpenId}->{stu["Lid"]}  {res.Result.ErrorMessage}").LogWarning();
            }));

        }

        /// <summary>
        /// 发送在线消息
        /// </summary>
        /// <param name="token"></param>
        private void OnlineNoticeMe(string token)
        {
            if (!send)
            {
                CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
                tplr.TemplateId = "ENpttNmhOaEhxCiUW0TN4a2_Gc3G6_-XKgrlZCrcHrk";
                tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
                // 头
                tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "服务器PAYMQTTclient上线了" });
                // 姓名
                tplr.Data.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "MQTT" });
                // 时间
                tplr.Data.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm") });
                // 地点
                tplr.Data.Add("keyword3", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "服务器" });
                // 备注
                tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "请注意查收" });
                tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
                tplr.AccessToken = token;
                //tplr.Url = "";

                var client = new WechatApiClient(options);
                client.ExecuteCgibinMessageTemplateSendAsync(tplr);

                send = true;
            }
        }


        /// <summary>
        /// 发送离校消息
        /// </summary>
        /// <param name="token"></param>
        private void LevelMsg(string token, DataRow stu, DataRow laos)
        {



            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.离校教师;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            // 头
            tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"{laos["username"]}您好: {stu["username"]}刚刚在{stu["address"]}附近出现。" });
            // 姓名
            tplr.Data.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = stu["username"].ToString(), Color = "#173177" });
            // 时间
            tplr.Data.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm") });
            // 地点
            tplr.Data.Add("keyword3", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = stu["address"].ToString() });
            // 备注
            tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = "如果孩子非正常离校,请及时处理。", Color = "#ff0000" });
#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
                tplr.ToUserOpenId = laos["oauth_id"].ToString();
#endif

            tplr.AccessToken = token;
            //tplr.Url = "";


            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr);


        }

        /// <summary>
        ///  校园群发通知 5分钟1次
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="count"></param>
        //[SpareTime(300000, "jobName2", StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        public void DoSomething2(SpareTimer timer, long count)
        {
            Scoped.Create((_, scope) =>
            {
                try
                {

                    var services = scope.ServiceProvider;
                    var response = (server + "/index.php/weixinsend/CoustomMessage").SetRequestScoped(services).GetAsStringAsync();
                    if (response.Result != "")
                    {
                        Console.WriteLine("校园通知" + response.Result);
                    }
                    response = (server + "/index.php/weixinsend/tele").SetRequestScoped(services).GetAsStringAsync();
                    if (response.Result != "")
                    {
                        Console.WriteLine("电话通知" + response.Result);
                    }

                }
                catch (Exception e)
                {

                    Console.WriteLine("校园通知 失败 " + e.Message);

                }
            });

            //Console.WriteLine("校园通知" + count);
        }

        /// <summary>
        ///  设备在线检测 10分钟一次
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="count"></param>
        //[SpareTime(600000, "jobName3", StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        public void Devchcek(SpareTimer timer, long count)
        {
            Console.WriteLine("job3");
            var h = DateTime.Now.Hour;
            if ((h < 6) || (h > 22))
            {

                return;

            }
            var options3 = App.GetOptionsMonitor<LxbOptions>();
            Console.WriteLine(options3);
            Scoped.Create((_, scope) =>
            {
                var services = scope.ServiceProvider;
                var dvck = services.GetService<DeviceCheck>();
                for (int i = 0; i < 2; i++)
                {

              
                    CgibinMessageTemplateSendRequest tplr = new();
                    foreach (var item in dvck.Getdevevent(i))
                    {
                      

                        tplr.TemplateId = TplIds.设备状态;
                        tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
                        // 头
                        tplr.Data.Add("first", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"{item.school} 设备状态发生变化" });
                        // 名
                        tplr.Data.Add("keyword1", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = item.name, Color = "#173177" });
                        // 状态
                        tplr.Data.Add("keyword2", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = item.state == 1 ? "在线" : "离线", Color = item.state == 1 ? "#FF0000" : "#173177" });
                        // 地点

                        // 备注
                        tplr.Data.Add("remark", new CgibinMessageTemplateSendRequest.Types.DataItem { Value = $"发生时间{item.ctime}", Color = "#ff0000" });


#if DEBUG
                        tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
                tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8"; //oyXHL0kSA5RKTQ0C29JQwVdqm_lA
#endif

                        tplr.AccessToken = token;
                        //tplr.Url = "";



                        dvck.delesend(item);

                     
                        var client = new WechatApiClient(options);
                        foreach (var optid in options3.openids)
                        {
                            Console.WriteLine(optid + " 通知");
                            tplr.ToUserOpenId = optid;
                            client.ExecuteCgibinMessageTemplateSendAsync(tplr);
                        }
                    }
                }

            });

            //Console.WriteLine("校园通知" + count);
        }

        /// <summary>
        ///  每天20:0分 
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="count"></param>
        [SpareTime("0 1 20 * * *", "Jiaofeichcek", CronFormat = CronFormat.IncludeSeconds, StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        //[SpareTime(30000, "Jiaofeichcek", StartNow = true, ExecuteType = SpareTimeExecuteTypes.Serial)]
        public void Jiaofeichcek(SpareTimer timer, long count)
        {

            Console.WriteLine("Jiaofeichcek");
            StringLoggingPart.Default().SetMessage("Jiaofeichcek").LogError();
            {
                // var services = scope.ServiceProvider;
                try
                {
                    var str = (dbredis.StringGet(key));
                    if (!String.IsNullOrEmpty(str))
                    {
                        var t = (Dictionary<object, object>)ps.Deserialize(str);
                        if (t.ContainsKey("access_token"))
                        {
                            token = t["access_token"].ToString();
                            // Console.WriteLine(token);
                            OnlineNoticeMe(token);
                            Console.ForegroundColor = ConsoleColor.White;

                            var wxtz = App.GetService<WeixinTongzhi>();// services.GetService<WeixinTongzhi>();
                            using (var unsend = wxtz.getEndsend())
                            {
                                                        
                                foreach (DataRow kaoqin in unsend.Rows)
                                {
                                    try
                                    {

                                        using (var untz = wxtz.getDaoqiTongzhi(kaoqin["user_id"].ToString()))
                                        {

                                            foreach (DataRow guanzhu in untz.Rows)
                                            {
                                           
                                                    BuildXufeiMsg(token, kaoqin, guanzhu);
                                             
                                               


                                            }


                                        }


                                    }
                                    catch (Exception e)
                                    {
                                        StringLoggingPart.Default().SetMessage($"{e.Message} ").LogError();

                                        Console.ForegroundColor = ConsoleColor.Red;
                                        Console.WriteLine(e.Message);
                                        Console.ForegroundColor = ConsoleColor.White;
                                    }
                                  
                                }

                            }
                        }
                    }

                }
                catch (Exception e)
                {
                    StringLoggingPart.Default().SetMessage($"{e.Message} ").LogError();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("微信通知 失败 " + e.Message);
                }

            }
        }
    }
}
